package com.example.wotu;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import static java.nio.charset.StandardCharsets.UTF_8;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragWLLookBook.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragWLLookBook#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragWLLookBook extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private View view;
    private TextView lookBook;
    private TextView bookleft;
    private TextView bookright;
    private TextView lookml;
    private int num = 0,booksize = 0;
    private String nas,urls,qzurl = "https://www.xbiquge.la";
    private ArrayList<String> bokna,bokurl;
    private Handler handler;
    private ScrollView lookbs;

    public FragWLLookBook() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragWLLookBook.
     */
    // TODO: Rename and change types and number of parameters
    public static FragWLLookBook newInstance(String param1, String param2) {
        FragWLLookBook fragment = new FragWLLookBook();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //******* 103 *******
        view = inflater.inflate(R.layout.frag_wllook_book, container, false);
        mListener.onNOT_WK(103);

        getArg();
        getFindL();
        nas = bokna.get(num);
        urls = qzurl+bokurl.get(num);
        getRUNNlook();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //1.要设置手机返回键时判断所处那个Fragment位置？
        //2.还是要二选一，打开Fragment，就要关闭layout。
        bookleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(num == 1) Toast.makeText(getActivity(),"这已经是第一章了！",Toast.LENGTH_SHORT).show();
                else{
                    num -= 1;
                    nas = bokna.get(num);
                    urls = qzurl+bokurl.get(num);
                    getRUNNlook();
                    lookbs.fullScroll(View.FOCUS_UP);
                }
            }
        });
        bookright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(num == booksize) Toast.makeText(getActivity(),"这已经最后一章了！",Toast.LENGTH_SHORT).show();
                else{
                    num += 1;
                    nas = bokna.get(num);
                    urls = qzurl+bokurl.get(num);
                    getRUNNlook();
                    lookbs.fullScroll(View.FOCUS_UP);
                }
            }
        });
    }

    //1.获取传递数据；2.实例id；3.数据接收；4.转换格式
    private void getArg(){
        num = getArguments().getInt("num");
        booksize = getArguments().getInt("numZJ");
        bokna = getArguments().getStringArrayList("ZJname");
        bokurl = getArguments().getStringArrayList("ZJ");
    }
    private void getFindL(){
        lookBook = view.findViewById(R.id.booklook);
        lookml = view.findViewById(R.id.bookzhj);
        lookml.setText((num+1)+" / "+booksize);
        bookleft = view.findViewById(R.id.bookleft);
        bookright = view.findViewById(R.id.bookright);
        lookbs = view.findViewById(R.id.lookBS);
    }
    private void getRUNNlook(){
        //笔趣阁
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                booksize = 0;
                Document document = null;
                try {
                    document = Jsoup.connect(urls).get();
                    Element contenta = document.getElementById("content");
                    handler.sendMessage(handler.obtainMessage(0,contenta));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        };
            new Thread(runnable).start();
            handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    if(msg.what == 0){
                        String text = UUTF(String.valueOf(msg.obj));
                        lookBook.setText(nas+"\n"+text);
                    }
                }
            };
    }
    //笔趣阁的正则式处理
    private String UUTF(String str){
        String o = str.replaceAll("&nbsp;","  ");
        String ao = o.replaceAll("<br>","");
        String bo = ao.replaceAll("<d.*>","");
        String co = bo.replaceAll("<p>.*</p>","");
        String dos = co.replaceAll("</div>","");
        return dos;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onNOT_WK(int wk);
    }
}
